import sys
import os
import logging
from PyQt6.QtWidgets import QApplication, QFileDialog, QMessageBox
from ui.commit_viewer import GitCommitViewer
from log_config import setup_logging
import json

setup_logging()
logger = logging.getLogger(__name__)


def main():
    app = QApplication(sys.argv)

    repo_path = ""
    while True:
        try:
            repo_path = sys.argv[1]
            break
        except IndexError:
            logger.info("未在命令行指定仓库路径")
        try:
            config_file_name = "config.json"
            config = json.load(open(config_file_name))
            repo_path = config["repo_path"]
            QMessageBox.information(
                None,
                "提示",
                f"""
仓库路径已配置为：{repo_path}
若要改变仓库路径，请修改{config_file_name}
或直接删除
""",
                QMessageBox.StandardButton.Ok,
            )

            break
        except:
            logger.info("未找到配置文件")
        break

    if not (repo_path and os.path.isdir(os.path.join(repo_path, '.git'))):
        repo_path = QFileDialog.getExistingDirectory(None, "选择 Git 仓库路径")
        json.dump({"repo_path": repo_path}, open("config.json", "w"))

    if not repo_path:
        logger.warning("未选择仓库，程序退出。")
        return

    try:
        window = GitCommitViewer(repo_path)
        window.show()
        sys.exit(app.exec())
    except Exception as e:
        logger.exception("程序发生异常：")
        QMessageBox.critical(None, "错误", f"程序出错：{str(e)}")


if __name__ == "__main__":
    main()
